package com.mall.interceptor;

import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.mall.untils.DateUtils;
/**
 * 
 * 安全验证
 * 登录拦截
 */
public class CommonInterceptor  implements HandlerInterceptor{
	private static Logger logger = LoggerFactory.getLogger(CommonInterceptor.class);
	private static final String LOGIN_URL = "/manager_login";  
	@Override
	public void afterCompletion(HttpServletRequest request,
			HttpServletResponse response, Object arg2, Exception arg3)
			throws Exception {
		// TODO Auto-generated method stub
	}
	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response,
			Object arg2, ModelAndView arg3) throws Exception {
		// TODO Auto-generated method stub
	}
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
			Object arg2) throws Exception {
		// TODO Auto-generated method stub
		HttpSession session = request.getSession();
		if(null!=session && null!=session.getAttribute("name") && !StringUtils.isEmpty(String.valueOf(session.getAttribute("name")))){
			//如果30分钟未进行任何操作，则需要从新登录
			String time = String.valueOf(session.getAttribute("time"));
			String timeNew=DateUtils.logStartTime();
			SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			Date now = df.parse(timeNew);
			Date date=df.parse(time);
		    long l=now.getTime()-date.getTime();
		    long day=l/(24*60*60*1000);
		    long hour=(l/(60*60*1000)-day*24);
			long min=((l/(60*1000))-day*24*60-hour*60);
			if(min>=30){
				//删除session
				logger.info("拦截器执行..长时间内无操作需要从新登录...当前登录人："+session.getAttribute("name")+"...上一次在线时间："+time+"..最后在线时间更新："+timeNew+"..执行者操作："+request.getRequestURI());
				session.removeAttribute("name");
				session.removeAttribute("time");
				response.sendRedirect(LOGIN_URL);  
				return false;
			}else{
				session.setAttribute("time", timeNew);
			}
			logger.info("拦截器执行.....当前登录人："+session.getAttribute("name")+"...上一次在线时间："+time+"..本次在线时间更新："+timeNew+"..执行者操作："+request.getRequestURI());
			return true;
		}else{
			logger.info("拦截器执行........未登录........");
			response.sendRedirect(LOGIN_URL);  
			return false;
		}
	}
	
}
